package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.Sound;
import com.tanhua.dubbo.api.mongo.SoundApi;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Sound sound) {
        mongoTemplate.save(sound);
    }

    @Override
    public Sound findSound(Long userId, String gender) {
        Integer status = 1;
        if ("woman".equals(gender)) {
            status = 0;
        }
        Query query = new Query(Criteria.where("status").is(status));
        List<Sound> soundList = mongoTemplate.find(query, Sound.class);
        if (soundList == null || soundList.size() == 0) {
            return null;
        }
        Integer count = 0;
        if (soundList.size() > 1) {
            count = RandomUtils.nextInt(0, soundList.size() - 1);
        }
        Sound sound = soundList.get(count);
        Query querySet = new Query(Criteria.where("id").is(sound.getId()));
        Update update = new Update();
        update.set("sendUserId", userId);
        update.set("status", 3);
        mongoTemplate.updateFirst(querySet, update, Sound.class);
        return sound;
    }
}
